<template>
  <div>
    <!-- 搜索框 -->
    <div style="height: 25px;line-height: 50px;margin:15px 0; display: flex;
              justify-content: center;
              align-items: center;">
      <el-input
        style="width: 200px;"
        clearable
        placeholder="请输入请假人员姓名"
        suffix-icon="el-icon-search"
        type="text"
        v-model="search">
  
      </el-input><el-button class="ml-5" type="primary" @click="load">搜索</el-button>
    </div>
    <!-- 新增 -->
    <div style="height: 50px;line-height: 50px;margin: 15px 0">
      <el-button type="primary" @click="add">新增<i class="el-icon-circle-plus-outline"></i></el-button>
    </div>
  
    <!-- 请假记录展示 -->
    <el-table
      :data="leaveData"
      style="width: 100%"
      v-loading="loading"
      :row-class-name="tableRowClassName"
      >
      <el-table-column prop="lid" label="请假单号" width="105px"></el-table-column>
      <el-table-column prop="name" label="姓名" width="80px"></el-table-column>
      <el-table-column prop="department" label="部门" width="100px"></el-table-column>
      <el-table-column prop="startday" label="请假开始日期" width="100px"></el-table-column>
      <el-table-column prop="endday" label="请假结束日期" width="100px"></el-table-column>
      <el-table-column prop="category" label="请假类别" width="100px"></el-table-column>
      <el-table-column prop="uname" label="审批人" width="100px"></el-table-column>
      <el-table-column prop="phone" label="审批人联系方式" width="100px"></el-table-column>
      <el-table-column prop="department1" label="审批人部门" width="100px"></el-table-column>
      <el-table-column prop="status" label="当前环节" width="100px"
                            :filters="[{ text: '待审批', value: '待审批' },
                                       { text: '已完成', value: '已完成' }]"
                                        :filter-method="filterButton"
                                        filter-placement="bottom-end">
        <template slot-scope="scope">
          <el-button style="margin: auto;" type="warning" round v-if="scope.row.status === '待审批'">待审批</el-button>
          <el-button style="margin: auto;" type="success" round v-else-if="scope.row.status === '已完成'">已完成</el-button>
        </template>

      </el-table-column>
      <el-table-column prop="attachment" label="附件证明" width="100px">
        <template #default="scope">
          <el-image 
          style="width: 100px; height: 100px  display: 'none'"
          :src= "scope.row.attachment"
          :preview-src-list="[scope.row.attachment]"
          preview-teleported="true"
          
          >
        </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          
          <el-button type="primary" icon="el-icon-edit" v-if="scope.row.status === '已完成'" :style="{ display: 'none' }" circle @click="handleEdit(scope.row)"/>
          <el-button type="primary" icon="el-icon-edit" v-if="scope.row.status === '待审批'" circle @click="handleEdit(scope.row)"/>
          <el-popconfirm title="确定删除记录吗" @confirm="handleDelete(scope.row.lid)">
            <template #reference>
              <el-button type="danger" icon="el-icon-delete" circle />
            </template>
          </el-popconfirm>
          <el-button type="success" icon="el-icon-check" 
                      v-if="scope.row.status === '待审批'" 
                      plain style="margin: auto;"
                      @click="finish(scope.row)">
                      审批
        </el-button>
          <el-button type="info" v-if="scope.row.status === '已完成'"
                      plain style="margin: auto;"
                      @click="finish(scope.row)">
                      详细信息
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  <!-- 分页 -->
    <div style="padding :10px 0; display:flex ;
              justify-content:center;
              align-items: center; ">
      <el-pagination
        style=" position: absolute;margin: auto"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next"
        :pager-count="7"
        :total="total">
      </el-pagination>
    </div>
  <!-- 请假申请添加 -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="50%">
  
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item  prop="button">
        <el-button  v-model="ruleForm.button" disabled>{{ this.ruleForm.button }}</el-button>
      </el-form-item>
        
        <el-form-item prop="name" label="请假人姓名">
          <el-input  v-model.number="ruleForm.name"></el-input>
        </el-form-item>
        
        <el-form-item label="部门" prop="department">
          <el-select v-model="ruleForm.department" placeholder="请选择所属部门">
            <el-option label="云平台维护室" value="云平台维护室"></el-option>
            <el-option label="现场组" value="现场组"></el-option>
            <el-option label="客户经理" value="客户经理"></el-option>
            <el-option label="人事部" value="人事部"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请假日期" prop="leaveday">
        <el-date-picker
          v-model="ruleForm.leaveday"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="GetLeaveTime">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="请假类型" prop="category">
        <el-radio-group v-model="ruleForm.category">
          <el-radio label="事假" class="el-icon-male"></el-radio>
          <el-radio label="病假" class="el-icon-female"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="附件图片" prop="attachment" >
        <el-upload
            ref="upload"
            action="http://localhost:8080/api/sys/leaves/fileUpload"
            :headers="{'token':token}"
            :on-success="uploadSuccess"
            :style="{ display: visible1 }">
            <el-button type="primary">点击上传</el-button>
        </el-upload>
        <el-button type="danger" @click="attachmentRemove" :style="{ display: visible }">{{ this.ruleForm.attachment }}</el-button>
      </el-form-item>
      
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
  
    </el-dialog>

    <el-dialog
      title="请假单信息"
      :visible.sync="dialogVisible1"
      width="60%"
      height="50%">
      <span>
        <el-descriptions class="margin-top" :column="3"  border>
        <el-descriptions-item label="请假单号">{{ this.descriptions.lid }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ this.descriptions.name }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ this.descriptions.department }}</el-descriptions-item>
        <el-descriptions-item label="请假类型">{{ this.descriptions.category }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">{{ this.descriptions.status }}</el-descriptions-item>
        <el-descriptions-item label="请假开始日">{{ this.descriptions.startday }}</el-descriptions-item>
        <el-descriptions-item label="请假结束日">{{ this.descriptions.endday }}</el-descriptions-item>
        <el-descriptions-item label="审批人">{{ this.descriptions.uname }}</el-descriptions-item>
        <el-descriptions-item label="审批人联系方式">{{ this.descriptions.phone }}</el-descriptions-item>
        <el-descriptions-item label="附件证明">
          <template>
          <el-image 
          style="width: 100px; height: 100px "
          :src= "this.descriptions.attachment"
          :preview-src-list="[this.descriptions.attachment]"
          preview-teleported="true"
          >
        </el-image>
        </template></el-descriptions-item>
      </el-descriptions>
      </span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible1 = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible1 = false">确定</el-button>
  </span>
    </el-dialog>
  </div>
  </template>
  
  <script>
  import request from "../../utils/request";
  
  
  export default {
    name: "UserList",
  
    data(){
      return{
        search: '',
        dialogVisible: false,
        dialogVisible1:false,
        leaveData: [],
        descriptions:[],
        visible: 'none',
        visible1: '',
        token: localStorage.getItem('Authorization'),
        user: JSON.parse(localStorage.getItem('user')),
        currentPage: 1,
        pageSize: 5,
        total: 0,
        ruleForm: {},
        rules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'change' },
          ],
          department: [
            { required: true, message: '请输入所属部门', trigger: 'change' },
          ],
          leaveday: [
            { required: true, message: '请选择请假日期', trigger: 'change' },
          ],
          category: [
            { required: true, message: '请选择请假类型', trigger: 'change' },
          ],
        },
        loading: true
  
    }
    },
    created() {
      this.load()
    },
    methods:{
      tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row';
        } else if (rowIndex === 3) {
          return 'success-row';
        }
        return '';
      },
      //格式化日期列
      dateFormatter(row,column){
        let datetime = row.entry;
        if(datetime){
          datetime = new Date(datetime);
          let y = datetime.getFullYear() + '-';
          let m = datetime.getMonth()+1 + '-';
          let d = datetime.getDate();
          return y + m + d;
        }
        return ''
      },
      GetLeaveTime(){
      if (this.ruleForm.leaveday != null){
        this.ruleForm.startday = this.ruleForm.leaveday[0];
        this.ruleForm.endday = this.ruleForm.leaveday[1];
      }
      },
      attachmentRemove(){
        this.$refs['upload'].clearFiles()
        this.ruleForm.attachment = ''
        this.visible = 'none'
      },
      uploadSuccess(res){
        console.log(res);
        this.ruleForm.attachment = res.data
        this.visible = ''
      },
      //页面加载时，将数据传输给后端，后端数据渲染res.data.records到前端tableData
      load(){
        request.get("/sys/leaves/selectAll",{
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            search: this.search
          }
        }).then(res => {
          //console.log(res)
          //console.log(this.search)
          this.leaveData = res.data.records
          this.loading = false
          // console.log(this.tableData)
          this.total = res.data.total
        })

        
      },
      //新增按钮触发事件 添加记录弹窗
      add(){
        this.ruleForm = {}
        this.ruleForm.button = "新增请假记录",
        this.dialogVisible = true;
        this.visible = 'none'
        this.$refs['upload'].clearFiles()
      },
      //将弹窗内ruleForm表单数据传给后端，后端将数据
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            switch(this.ruleForm.button){
          case '修改信息':
          this.ruleForm.startday = this.ruleForm.leaveday[0];
          this.ruleForm.endday = this.ruleForm.leaveday[1];
          request.put("/sys/leaves/update",this.ruleForm).then(res =>{
            //console.log(res);
            // console.log(this.ruleForm)
            if (res.code === '1'){
              this.$message({
                type: "success",
                message: "修改信息成功"
              })
            } else {
              this.$message({
                type: "error",
                message: res.msg
              })
            }
            this.load() //刷新
            this.dialogVisible = false
          });
          this.load() //刷新
          this.dialogVisible = false
          break;
          
          case '新增请假记录':
          request.post("/sys/leaves/add",this.ruleForm).then(res =>{
            console.log(res);
            console.log(this.ruleForm)
            if (res.code === '1'){
              this.$message({
                type: "success",
                message: "新增请假申请成功"
              })
            } else {
              this.$message({
                type: "error",
                message: res.msg
              })
            }
            this.load() //刷新
            this.dialogVisible = false
          });   
          break;

          case '详细信息':
          this.dialogVisible = false
          break;
        }  
          } else {
            console.log('error submit!!');
            return false;
          }
        });
        
      },
      //重置新增 表单内容
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //表格编辑功能
      handleEdit(row){
        row.leaveday = [row.startday,row.endday]
        this.ruleForm = JSON.parse(JSON.stringify(row)) //与之前对象隔离开,避免浅拷贝问题
        this.ruleForm.button = "修改信息"
        
        
        if(this.ruleForm.attachment != ''){
          this.visible = ''
        }
        this.dialogVisible = true;
      },
      
      //表格删除功能
      handleDelete(lid){
        console.log(lid)
        request.delete("/sys/leaves/delete/"+lid).then(res=>{
          if (res.code === '1'){
            this.$message({
              type: "success",
              message: "删除成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load()  //删除后重新加载
        })
      },
      //审批/详细信息按钮
      finish(row){
        this.ruleForm = JSON.parse(JSON.stringify(row))
        switch(this.ruleForm.status){
        case '待审批':
          this.ruleForm.uname = this.user.name
          this.ruleForm.phone = this.user.phone
        request.put("/sys/leaves/finish",this.ruleForm).then(res=>{
          if (res.code === '1'){
            this.$message({
              type: "success",
              message: "审批成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load()  //删除后重新加载
        })
        break;
        case '已完成':
        this.ruleForm = JSON.parse(JSON.stringify(row)) //与之前对象隔离开,避免浅拷贝问题
        this.ruleForm.leaveday = [this.ruleForm.startday,this.ruleForm.endday]
        this.descriptions = this.ruleForm
        this.dialogVisible1 = true
        break;
        }
        
      },
      // 表格筛选
      filterButton(value, row) {
      return row.status === value;
      },
      handleSizeChange(pageSize) {  //改变当前每页显示个数触发
        this.pageSize = pageSize;
          this.load()
      },
      handleCurrentChange(currentPage) {  //改变当前页码 触发
        this.currentPage = currentPage;
        this.load()
      }
    }
  }
  </script>
  
  <style>

  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  </style>
  